package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.ISetmealDishService;
import com.itheima.reggie.service.ISetmealService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private ISetmealService setmealService;
    @Autowired
    private ISetmealDishService setmealDishService;
    @Autowired
    private ICategoryService categoryService;
    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody SetmealDto setmealDto){
        //保存套餐的数据
        setmealService.save(setmealDto);
        //2、保存套餐菜品数据到 setmeal_dish表中： SetmealDishMapper
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        //2.1 获取当前套餐的菜品列表
        //2.2 循环遍历，获取每一个套餐菜品数据 setmealDish
        for (SetmealDish dish : dishes) {
            //2.3 获取套餐id，并set到setmealDish中
            dish.setSetmealId(setmealDto.getId());
        }
        //2.4 保存套餐菜品数据 setmealDish
        setmealDishService.saveBatch(dishes);
        return R.success(null);
    }
    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        ///创建page对象，设置当前页和每页大小
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        // 封装查询条件 where name like '%%'
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        //封装排序
        qw.orderByDesc(Setmeal::getUpdateTime);
        //开始查询
        setmealService.page(pageInfo,qw);
        //总条数
        long total = pageInfo.getTotal();
        //查询列表数据
        List<Setmeal> records = pageInfo.getRecords();
        Map map = new HashMap<>();
        map.put("total",total);
        //拉姆达表达式的写法
        List<SetmealDto> setmealDtos = records.stream().map((setmeal) -> {
            Long categoryId = setmeal.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            SetmealDto setmealDto = new SetmealDto();
            setmealDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(setmeal, setmealDto);
            return setmealDto;
        }).collect(Collectors.toList());
        map.put("records",setmealDtos);
        return R.success(map);
    }
    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids ){
        //1、判断当前要删除的套餐是否处于售卖状态，如果是，不允许删除
        // select count(*) from setmeal where id in (1,2,3) and status = 1
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            if (setmeal.getStatus()==1){
                return R.error("删除失败");
            }
        }
        //2、删除套餐： delete from setmeal where id in (1,2,3)
        setmealService.removeByIds(ids);
        //3、删除套餐对应的菜品数据：delete from setmeal_dish where setmeal_id in (1,2,3)
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SetmealDish::getSetmealId,id);
            setmealDishService.remove(lqw);
        }
        //setmealDishService.removeByIds(ids);
        return R.success("删除成功");
    }
    /**
     * 启售  停售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R updatestatus(@PathVariable Integer status ,@RequestParam List<Long> ids){
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("操作成功");
    }
    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get( @PathVariable Long id) {
        //1、根据套餐id查询套餐数据 select * from setmeal where id =?
        Setmeal setmeal = setmealService.getById(id);
        //2、根据套餐id查询套餐对应的菜品数据 select * from setmeal_dish where setmeal_id = ?
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(qw);
        //3、将套餐 setmeal 和套餐菜品集合 setmealDishList 数据封装到 SetmealDto并返回
        // 3.0 首先new一个SetmealDto对象
        SetmealDto setmealDto = new SetmealDto();
        // 3.1、BeanUtils.copyProperties() 拷贝setmeal到setmealDto中
        BeanUtils.copyProperties(setmeal,setmealDto);
        // 3.2、将setmealDishList 设置到 setmealDto中
        setmealDto.setSetmealDishes(list);
        //4、返回 setmealDto
        return R.success(setmealDto);
    }
    /**
     * 修改
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody SetmealDto setmealDto){
        //1、根据id更新 setmeal 套餐表数据 update setmeal set xx=?,.. where id =?
        setmealService.updateById(setmealDto);
        //2、操作套餐对应的菜品数据： setmeal_dish
        //2.1 先根据套餐id删除套餐对应的菜品数据： delete from setmeal_dish where setmeal_id =?
        // 获取套餐id   setmealDto.getId()
        Long id = setmealDto.getId();
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getId,id);
        // 使用 setmealDishMapper 根据套餐id进行删除 ：delete from setmeal_dish where setmeal_id =?
        setmealDishService.remove(qw);
        //2.2 重新添加新的套餐对应的菜品数据 insert setmeal_dish values (..)
        // setmealDto.getSetmealDishes() 获取套餐的菜品集合 List<SetmealDish>
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        // 遍历套餐菜品集合数据
        for (SetmealDish setmealDish : setmealDishes) {
            // 有没有数据需要set ： 设置套餐id  setSetmealId
            setmealDish.setSetmealId(id);
        }
            // 添加套餐菜品数据 insert
        setmealDishService.saveBatch(setmealDishes);
        return R.success("修改成功");
    }
    /**
     * 根据套餐分类id查询套餐分类下的套餐
     * @param categoryId
     * @param status
     * @return
     */
    @GetMapping("/list")
    public R<List<Setmeal>> get(Long categoryId,Integer status){
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(Setmeal::getStatus,1);
        qw.eq(Setmeal::getCategoryId, categoryId);
        List<Setmeal> list = setmealService.list(qw);
        return R.success(list);
    }
}
